package com.city.controller;

import com.wenhuacheng.platform.entity.City;
import com.wenhuacheng.platform.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/cities")
public class CityController {
    @Autowired
    private CityService cityService;

    @GetMapping("/")
    public Map<String, Object> listCities() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<City> cities = cityService.selectAll();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", cities);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/{id}")
    public Map<String, Object> getCity(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            City city = cityService.selectByPrimaryKey(id);
            if (city != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", city);
            } else {
                result.put("code", 404);
                result.put("message", "城市不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/hot")
    public Map<String, Object> getHotCities(@RequestParam(value = "limit", defaultValue = "3") int limit) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<City> cities = cityService.selectHotCities(limit);
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", cities);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败");
            e.printStackTrace();
        }
        return result;
    }
}